/*
package com.skyMailbox.sms.service.impl;

//import com.smsPremium.sms.service.SensorSerialPort;

import com.skyMailbox.sms.service.helper.ProcesadorMensajes;
import gnu.io.*;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

public class SensorSerialPortRXTX implements Runnable, SerialPortEventListener {
    final String CRLF = "\r\n";
    String incomeMessage = CRLF + "+CMTI:";
    String getMessage = "AT+CMGR=";
    String deleteMessage = "AT+CMGD=";
    String retrivedMessage = CRLF + "+CMGR";
    //String messageString = "AT+CMGL=\"ALL\"" + (char) 13;
    String messageString = "ATD" + (char) 13;
    RXTXCommDriver commDriver = null;
    gnu.io.SerialPort serialPort = null;
    InputStream inStream = null;
    OutputStream outStream = null;
    private int currentTimeout;
    CommPortIdentifier portID;
    Thread readThread;

    int baud;
    int dataBits;
    int stopBits;
    int parity;
    int flowcontrol;


    public SensorSerialPortRXTX() {

        try {
            setSerialPortParams(9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
            setFlowControlMode(SerialPort.FLOWCONTROL_NONE | SerialPort.FLOWCONTROL_NONE);
            openConnection();
            readThread = new Thread(this);
            readThread.start();
            write(messageString.getBytes());
        } catch (Exception e) {
            System.out.println("verror abriendo el puerto = " + e);
        }

    }

    public List getAvailablePorts() {

        List availablePorts = new ArrayList();

        if (commDriver == null) {
            commDriver = new RXTXCommDriver();
            commDriver.initialize();
        }

        Enumeration ports = CommPortIdentifier.getPortIdentifiers();
        while (ports.hasMoreElements()) {
            CommPortIdentifier portID = (CommPortIdentifier) ports.nextElement();
            System.out.println("RXTX: found serialPort: " + portID.getName());
            availablePorts.add(portID.getName());
        }

        return availablePorts;
    }

    public void openConnection() throws Exception {

        try {

            if (commDriver == null) {
                commDriver = new RXTXCommDriver();
                commDriver.initialize();

                Enumeration ports = CommPortIdentifier.getPortIdentifiers();
                while (ports.hasMoreElements()) {
                    portID = (CommPortIdentifier) ports.nextElement();
                    System.out.println("RXTX: found serialPort: " + portID.getName());
                }
            }

            if (serialPort != null) {
                // assert
                throw new RuntimeException("The serialPort was not closed before being opened");
            }

            //abro el puerto
            serialPort = (gnu.io.SerialPort) portID.open("SimpleWrite", 30000);
            //commDriver.getCommPort(portName, CommPortIdentifier.PORT_SERIAL);;

            // le coloco los parametros
            setConnectionParameters();

            // creo el outputStream de puerto serial
            outStream = serialPort.getOutputStream();

            // creo el de l puerto serial
            inStream = serialPort.getInputStream();


            serialPort.addEventListener(this);

            // se coloca a true notifyOnDataAvailable para manejador de eventos entre en accion
            serialPort.notifyOnDataAvailable(true);

            // se coloca a true notifyOnDataAvailable para que el manejador de eventos romapa la coneccion
            serialPort.notifyOnBreakInterrupt(true);

            serialPort.notifyOnCarrierDetect(true);
            serialPort.notifyOnCTS(true);
            serialPort.notifyOnDSR(true);
            serialPort.notifyOnFramingError(true);
            serialPort.notifyOnOutputEmpty(true);
            serialPort.notifyOnOverrunError(true);
            serialPort.notifyOnParityError(true);
            serialPort.notifyOnRingIndicator(true);

            //serialPort.enableReceiveTimeout(30);

        } catch (PortInUseException e) {
            System.out.println("Port in use.");
            serialPort.close();
        } catch (IOException e) {
            System.out.println("IOException outputStream.write " + e);
            serialPort.close();
        } catch (Exception e) {
            System.out.println("Exception.Thread  e" + e);
            System.out.println(e.toString());
            System.exit(-1);
            serialPort.close();
        }

    }

    public void open(String portName) throws Exception {
        if (commDriver == null) {
            commDriver = new RXTXCommDriver();
            commDriver.initialize();

            Enumeration ports = CommPortIdentifier.getPortIdentifiers();
            while (ports.hasMoreElements()) {
                CommPortIdentifier portID = (CommPortIdentifier) ports.nextElement();
                System.out.println("RXTX: found serialPort: " + portID.getName());
            }
        }

        if (serialPort != null) {
            // assert
            throw new RuntimeException("The serialPort was not closed before being opened");
        }

        System.out.println("RXTX: opening serialPort: " + portName);
        serialPort = (gnu.io.SerialPort) commDriver.getCommPort(portName, CommPortIdentifier.PORT_SERIAL);
        ;

        if (serialPort == null) {
            throw new Exception("can't open serial serialPort");
        }

        try {
            inStream = serialPort.getInputStream();
            outStream = serialPort.getOutputStream();
        } catch (IOException e) {
            throw new Exception("can't open streams", e);
        }

        try {
            serialPort.setSerialPortParams(baud, dataBits, stopBits, parity);
            serialPort.setFlowControlMode(flowcontrol);
        } catch (UnsupportedCommOperationException e) {
            throw new Exception("UnsupportedCommOperation", e);
        }

    }

    */
/* (non-Javadoc)
       * @see org.concord.sensor.dataharvest.DHSerialPort#close()
       *//*

    public void close() throws Exception {
        if (serialPort == null) {
            return;
        }
        serialPort.close();
        serialPort = null;
    }

    public boolean isOpen() {
        return serialPort != null;
    }

    */
/* (non-Javadoc)
       * @see org.concord.sensor.dataharvest.SerialPort#setSerialPortParams(int, int, int, int)
       *//*

    public void setSerialPortParams(int b, int d, int s, int p)
            throws Exception {
        baud = b;
        dataBits = d;
        stopBits = s;
        parity = p;
    }

    */
/* (non-Javadoc)
       * @see org.concord.sensor.dataharvest.SerialPort#getBaudRate()
       *//*

    public int getBaudRate() {
        return serialPort.getBaudRate();
    }

    */
/* (non-Javadoc)
       * @see org.concord.sensor.dataharvest.SerialPort#getDataBits()
       *//*

    public int getDataBits() {
        return serialPort.getDataBits();
    }

    */
/* (non-Javadoc)
       * @see org.concord.sensor.dataharvest.SerialPort#getStopBits()
       *//*

    public int getStopBits() {
        return serialPort.getStopBits();
    }

    */
/* (non-Javadoc)
       * @see org.concord.sensor.dataharvest.SerialPort#getParity()
       *//*

    public int getParity() {
        return serialPort.getParity();
    }

    */
/* (non-Javadoc)
       * @see org.concord.sensor.dataharvest.SerialPort#setFlowControlMode(int)
       *//*

    public void setFlowControlMode(int flowcontrol)
            throws Exception {
        this.flowcontrol = flowcontrol;
    }

    */
/* (non-Javadoc)
       * @see org.concord.sensor.dataharvest.SerialPort#disableReceiveTimeout()
       *//*

    public void disableReceiveTimeout() {
        serialPort.disableReceiveTimeout();
    }

    */
/* (non-Javadoc)
      * @see org.concord.sensor.dataharvest.SerialPort#enableReceiveTimeout(int)
       *//*

    public void enableReceiveTimeout(int time) throws Exception {
        currentTimeout = time;
        try {
            serialPort.enableReceiveTimeout(time);
        } catch (UnsupportedCommOperationException e) {
            throw new Exception("UnsupportedCommOperation");
        }
    }

    public int readBytes(byte[] buf, int off, int len, long timeout)
            throws Exception {
        // at least one of the receive time and theshold
        // don't work on windows.
        if (!System.getProperty("os.name").startsWith("Windows")) {
            try {
                serialPort.enableReceiveTimeout((int) timeout);
                serialPort.enableReceiveThreshold(len);

                int numRead = inStream.read(buf, off, len);

                serialPort.disableReceiveThreshold();
                serialPort.enableReceiveTimeout(currentTimeout);
                return numRead;
            } catch (UnsupportedCommOperationException e) {
                System.err.println("timeout or threshold not available on this platform");
            } catch (IOException e) {
                throw new Exception("threshold read error", e);
            }
        }

        // Fall back to polling method.
        // this method still assumes some form of timeout is supported
        // to handle no timeout support we'll need multiple threads.
        try {
            int size = 0;
            long startTime = System.currentTimeMillis();
            while (size != -1 && size < len &&
                    (System.currentTimeMillis() - startTime) < timeout) {
                int readSize = inStream.read(buf, size + off, len - size);
                if (readSize < 0) {
                    System.err.println();
                    System.err.println("error in readBytes: " + readSize);

                    return readSize;
                }
                size += readSize;
            }

            return size;
        } catch (IOException e) {
            throw new Exception("polling read error", e);
        }
    }

    public void write(byte[] buffer)
            throws Exception {
        try {
            outStream.write(buffer);
        } catch (IOException e) {
            throw new Exception("write error", e);
        }
    }

    public void write(byte[] buffer, int start, int length)
            throws Exception {
        try {
            outStream.write(buffer, start, length);
        } catch (IOException e) {
            throw new Exception("write error", e);
        }
    }

    public void write(int value)
            throws Exception {
        try {
            outStream.write(value);
        } catch (IOException e) {
            throw new Exception("write error", e);
        }
    }

    public void setConnectionParameters() throws Exception {
        serialPort.setSerialPortParams(9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
        serialPort.setFlowControlMode(SerialPort.FLOWCONTROL_NONE | SerialPort.FLOWCONTROL_NONE);

    }

    public void serialEvent(SerialPortEvent e) {

        long time = System.currentTimeMillis();
        // Create a StringBuffer and int to receive input data.
        StringBuffer inputBuffer = new StringBuffer();
        int newData = 0;

        System.out.println(e.getEventType());
        // Determine type of event.
        switch (e.getEventType()) {

            // Read data until -1 is returned. If \r is received substitute
            // \n for correct newline handling.

            case SerialPortEvent.DATA_AVAILABLE:
                System.out.println("");
                System.out.println("________________ START ____________");
                System.out.println("");


                while (newData != -1) {
                    try {
                        newData = inStream.read();
                        if (newData == -1) {
                            break;
                        }
                        inputBuffer.append((char) newData);
                    } catch (IOException ex) {
                        System.err.println(ex);
                        return;
                    }
                }

                String mensaje = new String(inputBuffer);

                try {
                    if (mensaje.startsWith(incomeMessage)) {
                        System.out.println("Llego un mensje en la posicion " + String.valueOf(mensaje.charAt(mensaje.indexOf(",") + 1)));
                        outStream.write((getMessage + String.valueOf(mensaje.charAt(mensaje.indexOf(",") + 1)) + CRLF).getBytes());
                    } else if (mensaje.startsWith(retrivedMessage)) {
                        Thread thread = new Thread(new ProcesadorMensajes(mensaje));
                        System.out.println("llamo run");
                        thread.start();
                        System.out.println("sale run");
                        outStream.write((deleteMessage + 1 + CRLF).getBytes());
                    }
                } catch (IOException es) {
                    System.out.println("e = " + es);
                }


                long time2 = System.currentTimeMillis() - time;
                System.out.println("");
                System.out.println("________________ END ____________" + time2 + " ms");


                break;

            // If break event append BREAK RECEIVED message.
            case SerialPortEvent.BI:
                System.out.println("--- BREAK RECEIVED ---");
        }


    }

    public void run() {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            System.out.println("e = " + e);
        }

    }
}*/
